package com.polaris.live.viewmodel

import androidx.lifecycle.MutableLiveData
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.UserTaskListV2Resp
import com.polaris.live.resp.bean.UserTaskActiveReceiveRewardBean
import com.polaris.live.resp.bean.UserTaskReceiveRewardBean
import com.polaris.live.resp.go_resp.TaskActiveReceiveRequest
import com.polaris.live.resp.go_resp.TaskReceiveRequest
import com.polaris.live.utils.TaskRedProxy

/**
 * TaskCenterViewModel
 *
 * @author Created by 半仙 on 2023/9/23/023 14:37
 */
class TaskCenterViewModel : BaseViewModel() {

    /**
     * 任务
     */
    var taskLiveData = MutableLiveData<ResultState<UserTaskListV2Resp>>()
    fun getTask() {
        requestLoading({ userService.getTaskV2() }, taskLiveData, waitTime = 0)
    }

    /**
     * 完成任务
     */
    var taskReceiveData = MutableLiveData<ResultState<UserTaskReceiveRewardBean>>()
    fun taskReceive(taskIds: List<Long>?, receiveUserReward: Boolean? = null) {
        requestLoading({ userService.taskReceive(TaskReceiveRequest(taskIds, receiveUserReward)) }, {
            taskReceiveData.value = ResultState.onAppSuccess(UserTaskReceiveRewardBean(taskIds, it, receiveUserReward))
            checkTaskRedShow()
        }, {
            it.ext = (it.ext?.toMutableMap() ?: mutableMapOf()).apply {
                taskIds?.let { ids ->
                    this["taskIds"] = ids
                }
                receiveUserReward?.let { receive ->
                    this["receiveUserReward"] = receive
                }
            }
            taskReceiveData.value = ResultState.onAppError(it)
            checkTaskRedShow()
        })
    }

    /**
     * 领取活跃奖励
     */
    var taskActiveReceiveData = MutableLiveData<ResultState<UserTaskActiveReceiveRewardBean>>()
    fun taskActiveReceive(activeValue: Long, dailyTask: Boolean) {
        requestLoading({ userService.taskActiveReceive(TaskActiveReceiveRequest(activeValue, dailyTask)) }, {
            taskActiveReceiveData.value =
                ResultState.onAppSuccess(UserTaskActiveReceiveRewardBean(activeValue, dailyTask, it))
            checkTaskRedShow()
        }, {
            it.ext = (it.ext?.toMutableMap() ?: mutableMapOf()).apply {
                this["activeValue"] = activeValue
                this["dailyTask"] = dailyTask
            }
            taskReceiveData.value = ResultState.onAppError(it)
            checkTaskRedShow()
        })
    }

    /**
     * 请求任务红点
     */
    private fun checkTaskRedShow() {
        request({ userService.getTaskNew() }, {
            TaskRedProxy.update(it)
        })
    }

}